package main.java;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.function.Function;

public class GenericFileHandler {
    // 写入文件：每行一个元素（调用element.toString()）
    public static <T> void writeToFile(DataContainer<T> container, String filePath) throws IOException {
        if (container == null || filePath == null || filePath.trim().isEmpty()) {
            throw new IllegalArgumentException("container and filePath cannot be null or empty");
        }
        // try-with-resources：自动关闭流，避免资源泄漏
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            for (int i = 0; i < container.size(); i++) {
                T element = container.get(i);
                // 元素为null时写入"null"，避免NPE
                String line = (element == null) ? "null" : element.toString();
                writer.write(line);
                writer.newLine(); // 每行一个元素
            }
        }
        // 无需手动关闭流，try-with-resources自动处理
    }

    // 从文件读取：通过parser将每行字符串转为T类型
    public static <T> DataContainer<T> readFromFile(String filePath, Function<String, T> parser) throws IOException {
        if (filePath == null || filePath.trim().isEmpty() || parser == null) {
            throw new IllegalArgumentException("filePath and parser cannot be null or empty");
        }
        DataContainer<T> result = new DataContainer<>();
        // try-with-resources：自动关闭BufferedReader
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            // 逐行读取，直到文件末尾
            while ((line = reader.readLine()) != null) {
                // 跳过空行（可选，根据需求调整）
                if (line.trim().isEmpty()) {
                    continue;
                }
                // 通过parser转换字符串为T类型
                T element = parser.apply(line);
                result.add(element);
            }
        }
        return result;
    }
}